#define _CRT_SECURE_NO_WARNINGS 1
#include"Stack.h"

static StackNode* CreatNode(StackDataType x)
{
	StackNode* newnode=malloc(sizeof(StackNode));
	if (newnode == NULL)
	{
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}

StackNode* StackInit()
{
	StackNode* phead = CreatNode(0);
	return phead;
}

void StackDestroy(StackNode** pphead)
{
	assert(pphead);
	assert(*pphead);
	StackNode* cur = *pphead;
	StackNode* next=NULL;
	while (cur)
	{
		next = cur->next;
		free(cur);
		cur = next;
	}
	*pphead = NULL;
}

void StackPush(StackNode* phead, StackDataType x)
{
	assert(phead);
	StackNode* newnode = CreatNode(x);
	newnode->next= phead->next;
	phead->next = newnode;
}

void StackPop(StackNode* phead)
{
	assert(phead);
	if (phead->next == NULL)
	{
		return;
	}
	StackNode* next = phead->next->next;
	free(phead->next);
	phead->next = next;
}

StackDataType StackTop(StackNode* phead)
{
	assert(phead && phead->next);
	return phead->next->data;
}

int StackSize(StackNode* phead)
{
	assert(phead);
	int ret = 0;
	StackNode* cur = phead->next;
	while (cur)
	{
		ret++;
		cur = cur->next;

	}
	return ret;
}

bool StackEmpty(StackNode* phead)
{
	assert(phead);
	return phead->next;
}

void StackClear(StackNode* phead)
{
	assert(phead);
	StackNode* cur = phead->next;
	while (cur)
	{
		StackNode* next = cur->next;
		free(cur);
		cur = next;
	}
	phead->next = NULL;
}

